package com.ews.onlineexchange.service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;

@Stateless
public class SupplierApplyService implements Serializable {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;
	
	@Inject
	EntityManager				entityManager;
	
	@Inject
	UserService					userService;
	
	@Inject
	TradeSeqNoGenerator			tradeSeqNoGenerator;

	@Transactional
	public void applyTrade( Bulletin bulletin ) throws ConflictingSupplierException {
		ServiceSupplier loginedUser = (ServiceSupplier) userService.getLoginedUser();
		List<Bulletin> conflictBulletinList = queryConflictBulletin( bulletin.getRootConflictingBulletin().getId(), loginedUser.getId() );
		if ( conflictBulletinList.size() > 0 ) {
			throw new ConflictingSupplierException( conflictBulletinList.get( 0 ).getProjectName() );
		}
		
//		bulletin.setHasAppliedCount( bulletin.getAppliedCount() + 1 );
		entityManager.merge( bulletin );

		Trade trade = new Trade();		
		trade.setSupplier( loginedUser );
		trade.setBulletin( bulletin );
		trade.setSerialNumber( tradeSeqNoGenerator.getNextSeqNo() );
		trade.setApply( true );
		trade.setApplyTime( new Date() );
		trade.setHasVerify( true );
		trade.setApplyTime( new Date() );
		entityManager.persist( trade );
		entityManager.flush();
	}
	
	private static final String QUERY_CONFLICT_BULLETIN_EQL = ""
			+ "	SELECT			b	"
			+ " FROM			Bulletin b	"
			+ "	WHERE		(	b.conflictingBulletin.id = :rootConflictBulletinId OR b.id = :rootConflictBulletinId ) "
			+ "	AND				b.successTrade.supplierId = :supplierId ";
	private List<Bulletin> queryConflictBulletin ( String rootId, String supplierId ) { 
		Query query = entityManager.createQuery( QUERY_CONFLICT_BULLETIN_EQL );
		query.setParameter( "rootConflictBulletinId", rootId );
		query.setParameter( "supplierId", supplierId );
		return query.getResultList();
	}

}
